package com.ruoyi.common.utils.wms;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义反序列化器，用于将JSON数组、字符串或数字转换为逗号分隔的字符串
 * &#064;Author:  mwj
 */
public class CustomRegionIdsDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        JsonNode node = mapper.readTree(p);

        // 处理数组情况
        if (node.isArray()) {
            List<String> regionIdsList = new ArrayList<>();
            for (JsonNode idNode : node) {
                regionIdsList.add(idNode.asText());
            }
            return String.join(",", regionIdsList);
        }

        // 处理字符串情况
        if (node.isTextual()) {
            return node.asText();
        }

        // 处理数字情况
        if (node.isNumber()) {
            return node.asText();
        }

        // 如果节点是null或其它类型，返回空字符串
        return "";
    }
}